﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ImdbServices;

namespace InsertIMDBInfo
{
    public partial class frmMain : Form
    {
        IMDB imdb;
        string url = string.Empty;
        Movie m_selectedmovie = null;
        PluginSettings m_settings;
        public Image Thumbnail = null;

        public frmMain(PluginSettings settings)
        {
            imdb = new IMDB();
            m_settings = settings;
            InitializeComponent();
            imdb.MovieInfoDownloaded += new IMDB.MovieInfoDownloadedEventHandler(imdb_MovieInfoDownloaded);
            imdb.SearchResultsDownloaded += new IMDB.SearchResultsDownloadedEventHandler(imdb_SearchResultsDownloaded);
        }

        void imdb_SearchResultsDownloaded(MoviesResultset M)
        {
            tvSearchResults.Nodes.Clear();
            if (M.ExactMatches.Count > 0 ||
                M.PartialMatches.Count > 0 ||
                M.PopularTitles.Count > 0)
            {
                SetError("", false);
                foreach (Movie movie in M.ExactMatches)
                {
                    TreeNode node = new TreeNode(movie.Title);
                    node.Tag = movie;
                    tvSearchResults.Nodes.Add(node);
                }
                foreach (Movie movie in M.PartialMatches)
                {
                    TreeNode node = new TreeNode(movie.Title);
                    node.Tag = movie;
                    tvSearchResults.Nodes.Add(node);
                }
                foreach (Movie movie in M.PopularTitles)
                {
                    TreeNode node = new TreeNode(movie.Title);
                    node.Tag = movie;
                    tvSearchResults.Nodes.Add(node);
                }
            }
            else
            {
                SetError("No results found. Try broadening your search.", true);
            }
            btnSearch.Enabled = true;
        }

        void imdb_MovieInfoDownloaded(Movie M)
        {
            ProcessMovie(M);
            //lblTitle.Text = string.Format("Film Title: {0}", M.Title);
            btnGetInfo.Enabled = true;
        }

        private void ProcessMovie(Movie M)
        {
            ShowCheckBoxes();
            // Set the Movie for insertion
            m_selectedmovie = M;
            // Film Title
            chbxTitle.Text = M.Title;
            // Film Url
            url = string.Format("http://www.imdb.com/title/tt{0}/", M.ImdbID);

            // Film Image
            if (string.IsNullOrEmpty(M.ImageURL))
            {
                M.ImageURL = "http://ia.media-imdb.com/media/imdb/01/I/37/58/83/10.gif";
            }
            chbxImage.Visible = true;
            try
            {
                Thumbnail =
                    Image.FromStream(
                    new System.IO.MemoryStream(
                        new System.Net.WebClient().DownloadData(M.ImageURL)));
                chbxImage.Image = Thumbnail;
            }
            catch
            {
                SetError("There was a problem getting the image.", true);
            }

            // Film's Actors
            string actors = string.Empty;
            int i = 0;
            if (M.Actors.Count > 0)
            {
                foreach (Person actor in M.Actors)
                {
                    if (i < 6)
                    {
                        actors += actor.Name;
                        if (i < M.Actors.Count - 1)
                            actors += ", ";
                        i++;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            else
            {
                actors += "No actors associated to this film.";
            }
            chbxActors.Text = actors;

            // Film Description
            chbxDescription.Text = M.Description;

            // Film Year
            chbxYear.Text = string.Format("Released: {0}", M.Year.ToString());
        }

        private void ShowCheckBoxes()
        {
            chbxTitle.Visible = true;
            chbxImage.Visible = true;
            chbxActors.Visible = true;
            chbxDescription.Visible = true;
            lnklblImdbLink.Visible = true;
            chbxYear.Visible = true;
            SetCheckBoxes();
        }

        private void SetCheckBoxes()
        {
            bool[] options = m_settings.ParseTemplateOptions(m_settings.DefaultTemplate);
            chbxActors.Checked = options[0];
            chbxDescription.Checked = options[1];
            chbxImage.Checked = options[2];
            chbxTitle.Checked = options[3];
            chbxYear.Checked = options[4];
        }

        private void btnGetInfo_Click(object sender, EventArgs e)
        {
            string url = txbxIMDBUrl.Text;
            if (!string.IsNullOrEmpty(url))
            {
                SetError("", false);
                if (CheckForIMDB(url))
                {
                    SetError("", false);
                    long code = GetCode(url);
                    imdb.GetMovieInfoAsync(code);
                    btnGetInfo.Enabled = false;
                }
                else
                {
                    SetError("Link was not a valid IMDb link.", true);
                }
            }
            else
            {
                SetError("No valid link was entered.", true);
            }
        }

        private bool CheckForIMDB(string url)
        {
            string domain = url.Substring(7, url.Length - 7);
            if (domain.Contains("imdb.com") && domain.Contains("tt"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private long GetCode(string url)
        {
            string c = url.Substring(url.LastIndexOf("tt") + 2, 7);
            return (long)Convert.ToInt32(c);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            SetError("", false);
            string search = txbxSearch.Text;
            if (!string.IsNullOrEmpty(search))
            {                
                imdb.SearchMovieAsync(search, chbxPartial.Checked, chbxExact.Checked);
                btnSearch.Enabled = false;
            }
            else
            {
                SetError("No search criteria entered.", true);
            }
        }

        private void SetError(string message, bool visible)
        {
            lblError.Text = message;
            lblError.Visible = visible;
        }

        private void tvSearchResults_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (tvSearchResults.SelectedNode != null)
            {
                SetError("", false);
                Movie movie = e.Node.Tag as Movie;
                imdb.GetMovieInfoAsync(movie.ImdbID);
            }
        }

        private void lnklblImdbLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.UseShellExecute = true;
            process.StartInfo.FileName = url;
            process.Start();
        }

        private void btnInsert_Click(object sender, EventArgs e)
        {
            if (m_selectedmovie == null)
            {
                SetError("No movie has been selected.", true);
                return;
            }
            else
            {
                SetError("", false);
                m_settings.Actors = chbxActors.Text;
                m_settings.Description = chbxDescription.Text;
                string displayoptions = string.Format("{0},{1},{2},{3},{4}",
                                                      chbxActors.Checked.ToString(),
                                                      chbxDescription.Checked.ToString(),
                                                      chbxImage.Checked.ToString(),
                                                      chbxTitle.Checked.ToString(),
                                                      chbxYear.Checked.ToString());
                m_settings.CustomTemplate = displayoptions;
                //m_settings.DisplayActors = chbxActors.Checked;
                //m_settings.DisplayDescription = chbxDescription.Checked;
                //m_settings.DisplayImage = chbxImage.Checked;
                //m_settings.DisplayTitle = chbxTitle.Checked;
                //m_settings.DisplayYear = chbxYear.Checked;
                m_settings.ImageUrl = m_selectedmovie.ImageURL;
                m_settings.IMDbLink = url;
                m_settings.Title = chbxTitle.Text;
                m_settings.Year = chbxYear.Text;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }
    }
}
